package com.bs.jianli.service.impl;

import com.bs.jianli.entity.User;
import com.bs.jianli.mapper.UserMapper;
import com.bs.jianli.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bs.jianli.util.UUIDFactory;
import com.bs.jianli.util.exception.NoAuthException;
import com.bs.jianli.util.exception.NotUserException;
import com.bs.jianli.util.jwt.JwtUtil;
import com.bs.jianli.util.redis.RedisUtils;
import com.bs.jianli.util.redis.TokenUtil;
import com.bs.jianli.util.security.LoginUser;

import jdk.nashorn.internal.parser.Token;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author yao
 * @since 2023-01-13
 */
@Service("auth")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    AuthenticationManager manager;

    @Resource
    RedisUtils utils;

    @Resource
    HttpServletRequest request;
    @Override
    public Map<String,Object> login(User user) {
        UsernamePasswordAuthenticationToken userpwd=new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        if(Objects.isNull(userpwd)){
            throw new NotUserException("用户名或密码错误");
        }
        Authentication authenticate = manager.authenticate(userpwd);
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        if(Objects.isNull(loginUser)){
            throw new NotUserException("用户名或密码错误");
        }
        //String jwt = JwtUtil.createJWT(loginUser.getUser().getUsername());
        String token = UUIDFactory.UUID();
        utils.set(token,loginUser);
       Map<String,Object> maps=new HashMap<>();
       maps.put("token",token);
       maps.put("user",loginUser);
        return maps;
    }

    @Override
    public String edit() {
        String token = request.getHeader(TokenUtil.TOKEN_NAME);
        utils.del(token);
        return "退出成功";
    }


    public boolean getAuth(String auth){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser =(LoginUser) authentication.getPrincipal();
       if(Objects.isNull(loginUser)){
           throw new NotUserException("您还未登录");
       }
        Set<String> pression = loginUser.getUser().getPression();
       if(!pression.contains(auth)){
            throw new NoAuthException("你没有该权限，请先申请权限");
       }
       return true;

    }
}
